<?php
/**
 * Author: FoxxxZhu
 * Date: 2016/10/10
 * Time: 17:58
 */
include_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'sphinxapi.php');

class SearchPost {
    public $sphinxClient = null;
    public $config = [];
    public $error = '';
    public function __construct($config = [])
    {
        $this->sphinxClient = new SphinxClient();
        $defaultConfig = self::getDefaultConfig();
        $this->config = array_merge($defaultConfig,$config);
        $this->sphinxClient->SetServer($this->getConfig('host'), $this->getConfig('port'));
        $this->sphinxClient->SetConnectTimeout($this->getConfig('timeout'));
        $this->sphinxClient->setMaxQueryTime($this->getConfig('maxQueueTime'));
        $this->sphinxClient->SetArrayResult($this->getConfig('arrayResult'));
        $this->sphinxClient->SetFieldWeights($this->getConfig('weights')); //权重数组
        $this->sphinxClient->SetSortMode($this->getConfig('sortMode'), $this->getConfig('sortBy'));
        $this->sphinxClient->SetMatchMode($this->getConfig('matchMode'));
        $this->sphinxClient->SetRankingMode($this->getConfig('rankingMode'));
    }

    public function get($word,$page = 1 , $size = 20)
    {
        $this->error = '';
        $word = trim($word);
        if(empty($word))
        {
            return null;
        }
        $this->sphinxClient->SetLimits(($page-1)*$size, $size,$this->getConfig('maxSize'));
        $res = $this->sphinxClient->query($word,$this->getConfig('source'));
        if (!$res)
        {
            $this->error = $this->sphinxClient->GetLastError();
            return [];
        }
        $ids = array_keys($res['matches']);
        return $ids;
    }

    public function getConfig($key,$default = null)
    {
        if(isset($this->config[$key]))
        {
            return $this->config[$key];
        }
        return $default;
    }

    public static function getDefaultConfig()
    {
        return [
            'host' => 'localhost',
            'port' => 9312 ,
            'source' => 'music_post',
            'timeout' => 1,
            'maxQueryTime' => 10,
            'arrayResult' => true,
            'weights' => [
                'name'=>1000,
                'tag'=>500,
                'keyword'=>800,
                'content'=>100,
                'remark'=>80,
            ],
            'sortMode'=>SPH_SORT_EXTENDED,
            'sortBy'=> '@weight DESC, created DESC',
            'matchMode'=>SPH_MATCH_EXTENDED2,
            'rankingMode'=>SPH_RANK_MATCHANY,
            'maxSize'=>5000,
        ];
    }
}